package com.nip.irregularvebsdict.ui;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import com.nip.irregularvebsdict.R;

public class NIPIrregularVebsDictActivity extends Activity {

	protected static final int SHOW_INTERSTITIAL = 4;
	private VerbsFragment verbsFragment;
	private FragmentManager manager;
	private FragmentTransaction fragmentTransaction;
	private InterstitialAd mInterstitial;
	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_irregular_vebs_dict);
		initialize();
	}

	private void initialize() {
		createFragment();
		mInterstitial = new InterstitialAd(this);
		mInterstitial.setAdUnitId("ca-app-pub-2476589568288062/5311721237");
		mInterstitial.setAdListener(new AdListener() {
			@Override
			public void onAdFailedToLoad(int errorCode) {
				super.onAdFailedToLoad(errorCode);
			}

			@Override
			public void onAdLoaded() {
				super.onAdLoaded();
			}
		});

		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				if (msg.what == SHOW_INTERSTITIAL) {
					showInterstitial();
					mInterstitial.loadAd(new AdRequest.Builder().build());
				}
				super.handleMessage(msg);
			}

		};
		handler.removeCallbacks(showInterHandle);
		handler.postDelayed(showInterHandle, 600000l);
		mInterstitial.loadAd(new AdRequest.Builder().addTestDevice("B04DDD10BB1F34C5737EC4C90B490AB9").build());
	}

	private Runnable showInterHandle = new Runnable() {

		@Override
		public void run() {
			handler.sendEmptyMessage(SHOW_INTERSTITIAL);
			handler.postDelayed(showInterHandle, 600000l);
		}
	};

	protected void showToast(String string) {
		Toast.makeText(getApplication(), string, Toast.LENGTH_SHORT).show();
	}

	private void createFragment() {
		verbsFragment = new VerbsFragment();
		manager = getFragmentManager();
		fragmentTransaction = manager.beginTransaction();
		fragmentTransaction.replace(R.id.container, verbsFragment);
		fragmentTransaction.commit();

	}

	@Override
	protected void onDestroy() {
		handler.removeCallbacks(showInterHandle);
		System.gc();
		super.onDestroy();
	}

	void showInterstitial() {
		if (mInterstitial != null && mInterstitial.isLoaded()) {
			mInterstitial.show();
		}
	}
}
